package com.group.elmboot.scheduled;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import com.group.elmboot.mapper.UserMapper;
import com.group.elmboot.mapper.WalletMapper;
import com.group.elmboot.po.User;
import com.group.elmboot.po.Wallet;
import com.group.elmboot.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class Task {
	
	@Autowired
	UserMapper userMapper;
	@Autowired
	WalletMapper walletMapper;
	@Value("myapp.globalVar.overdraftInterestDayly")
	String interestRate;
	@Value("myapp.globalVar.Interest_freeDays")
	String freeDays;
	
	@Scheduled(cron="0 0/1 * * * ?")
	public void VIPCheckAndExpiration() {
		List<User> VIPusers=userMapper.getVIPUsers();
		for(int i=0;i<VIPusers.size();i++) {
			User user=VIPusers.get(i);
			String expir=user.getExpirationTime();
			String curr= CommonUtil.getCurrentDate();
			Date current=null;
			Date expiration=null;
			try {
				current=CommonUtil.sdf.parse(curr);
				expiration =CommonUtil.sdf.parse(expir);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if(current.compareTo(expiration)>0) {
				Wallet wallet=walletMapper.selectById(user.getUserId());
				wallet.closeOverdraft();
				walletMapper.updateById(wallet);
				userMapper.updateExpirationTimeById(user.getUserId(), expir, 0);
			}
			
		}
	}
	
	@Scheduled(cron="0 0 12 * * ?")
	public void Interst() {//每一天12：00结算利息
		List<Wallet> overdraftUsers=walletMapper.getOverdraftUsers();
		for(int i=0;i<overdraftUsers.size();i++) {
			Wallet user=overdraftUsers.get(i);
			String overdraft=user.getOverdraftTime();
			DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime overdraftTime=LocalDateTime.parse(overdraft, dtf);
			LocalDateTime current=LocalDateTime.now();
			if(current.minusDays(Integer.parseInt(freeDays)).compareTo(overdraftTime) > 0) {
				try {
					user.interest(new BigDecimal(interestRate));
				} catch (Exception e) {
					e.printStackTrace();
				}
				walletMapper.updateById(user);
			}
			
		}
	}
	
}
